package com.north.light.androidxvp.network.base

import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.core.ObservableSource
import io.reactivex.rxjava3.functions.Function
import java.util.concurrent.TimeUnit

/**
 * create by lzt
 * date 2019/12/22
 */
class RetryWithDelay(private val maxRetries: Int, private val retryDelayMillis: Int) :
        Function<Observable<Throwable?>, ObservableSource<*>> {
    private var retryCount = 0
    override fun apply(throwableObservable: Observable<Throwable?>): ObservableSource<*> {
        return throwableObservable.flatMap(Function<Throwable?, ObservableSource<*>> { throwable ->
            try {
                if (throwable is TokenException) {
                    if (++retryCount <= maxRetries) {
//                            String phone = LoginRecord.Companion.getInstance().getPhone();
//                            NetWorkUtils.getInstance().refreshToken(phone)
//                                    .subscribeOn(Schedulers.io())
//                                    .observeOn(AndroidSchedulers.mainThread())
//                                    .subscribe(new DisposableObserver<BaseResult<String>>() {
//                                        @Override
//                                        public void onNext(BaseResult<String> value) {
//                                            LogUtil.d(TAG, "retryWhen data: " + new Gson().toJson(value));
//                                            LoginRecord.Companion.getInstance().setSpToken(value.getData());
//                                        }
//
//                                        @Override
//                                        public void onError(Throwable e) {
//
//                                        }
//
//                                        @Override
//                                        public void onComplete() {
//
//                                        }
//                                    });
//                            LogUtil.d(TAG, "retryWhen retryCount: " + retryCount);
                        return@Function Observable.timer(retryDelayMillis.toLong(), TimeUnit.MILLISECONDS)
                    }
                }
            } catch (e: Exception) {
                //LogUtil.d(TAG, "retryWhen error: " + e);
            }
            Observable.error<Any>(throwable)
        })
    }

    companion object {
        private val TAG = RetryWithDelay::class.java.name
    }

}